package zhan.redis;

import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.concurrent.TimeUnit;

/**
 * redies 工具类
 */
public class RedisUtil {

    private static RedisTemplate<String, Object> redisTemplate;


    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 指定缓存失效时间
     *
     * @param key
     * @param time 秒
     * @return
     */
    public boolean exprie(String key, long time) {

        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 取出缓存数据
     * @param key
     * @return
     */
    public static Object get(String key) {
        Object o = redisTemplate.opsForValue().get(key);
        return o;
    }


    /**
     * 存入缓存数据
     * @param key
     * @param value
     */
//    public static void set(String key,Object value){
//        redisTemplate.opsForValue().set(key,value);
//    }
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<String, Object> operations = redisTemplate.opsForValue();//opsForList();//opsForValue();
            //ListOperations<String, Object> opsForList = redisTemplate.opsForList();
            operations.set(key, value);
            //opsForList.leftPushAll(key, value);

            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public boolean exists(String key) {
        return redisTemplate.hasKey(key);
    }
}
